//
//  MyOrderViewController.m
//  Findif
//
//  Created by Mac on 2018/11/1.
//  Copyright © 2018年 Cicel Chen. All rights reserved.
//

#import "MyOrderViewController.h"
#import "MyOrderTopView.h"
#import "MyOrderListTableViewCell.h"
#import "ShopOrderModel.h"
#import "OrderDetailsViewController.h"
#import "ShopDetailsViewController.h"
#import "publishCommitViewController.h"
#import <CommonCrypto/CommonDigest.h>
#import "WXApiRequestHandler.h"
#import "WXApi.h"
//首先导入头文件信息
#include <ifaddrs.h>
#include <arpa/inet.h>
//#include <net/if.h>
#import "WXApiManager.h"
#import <AlipaySDK/AlipaySDK.h>
#import "DoneDetailViewController.h"

@interface MyOrderViewController ()<UITableViewDelegate,UITableViewDataSource,MyOrderTopViewDelegate,MyOrderListTableViewCellDelegate,WXApiManagerDelegate>

@property (nonatomic, weak)UITableView * tableView;
@property (nonatomic, strong)NSArray<ShopOrderModel *> * orderModelArray;
@property (nonatomic, weak)UIToolbar *toolbar;
@property (nonatomic, weak)UIView * whiteView;
@property (nonatomic, weak)UIToolbar * chooseToolbar;
@property (nonatomic, weak)UIView * chooseView;
@property (nonatomic, copy)NSString * type;
@property (nonatomic, copy)NSString * ID;
@property (nonatomic ,strong)dispatch_source_t timer;

@end

@implementation MyOrderViewController

- (void)viewWillAppear:(BOOL)animated{
    
    [self loadDataWithStatus:@"10"];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
//    self.orderModelArray = [NSMutableArray array];
    self.view.backgroundColor = ColorWithRGB(0xF5F5F5);
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(zhifuNotification:) name:@"zhifuNotification" object:nil];
    
    self.type = @"10";
    [self setupNav];
    [self setupUI];
}


- (void)loadDataWithStatus:(NSString *)status{
    
    NSString * user_id = DEF_GET_OBJECT(@"id");
    
    [[ZRNetworkTool sharedTool] getGoodsOrderListResultWithUser_id:user_id WithStatus:status WithBlock:^(BOOL success, id responseData) {
        
//        NSLog(@"res===%@",responseData);
        if (success) {

            self.orderModelArray = [NSArray yy_modelArrayWithClass:[ShopOrderModel class] json:responseData[@"data"]];
//            self.orderModelArray = [NSMutableArray arrayWithArray:array];
        }
    }];
}


- (void)setOrderModelArray:(NSArray<ShopOrderModel *> *)orderModelArray{
    
    _orderModelArray = orderModelArray;
    
    [self.tableView reloadData];
}

- (void)setupNav{
    
    self.title = @"我的订单";
    
//    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back(1)"] style:UIBarButtonItemStylePlain target:nil action:nil];
//    
//    self.navigationItem.backBarButtonItem = backItem;
}


- (void)setupUI{
    
    UITableView * tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.backgroundColor = ColorWithRGB(0xF5F5F5);
    tableView.rowHeight = 230 * SCREENH6;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableView.showsVerticalScrollIndicator = NO;
    
    self.tableView = tableView;
    
    
    [self.tableView registerClass:[MyOrderListTableViewCell class] forCellReuseIdentifier:@"MyOrderListTableViewCell"];
     [self.tableView registerClass:[MyOrderTopView class] forHeaderFooterViewReuseIdentifier:@"MyOrderTopView"];
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        [self updateData];
    }];
    
    [self.view addSubview:self.tableView];
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    //    NSLog(@"=====%lu",(unsigned long)self.goodlistArray.count);
    return self.orderModelArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    MyOrderListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyOrderListTableViewCell" forIndexPath:indexPath];
    
    cell.model = self.orderModelArray[indexPath.row];
    cell.myOrderListTableViewCellDelegate = self;
//    __weak typeof(self) weakSelf = self;
    
//    cell.clickSureButtonBlock = ^(MyOrderListTableViewCell * cell) {
//
//        [weakSelf cellClickSureButton:cell];
//    };
//
//    cell.clickCancleButtonBlock = ^(MyOrderListTableViewCell * cell) {
//
//
//        [weakSelf cellClickCancleButton:cell];
//    };
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 40 * SCREENH6;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    MyOrderTopView * header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"MyOrderTopView"];
    header.myOrderTopViewDelegate = self;
    return header;
}

- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section {
    if ([view isKindOfClass:[UITableViewHeaderFooterView class]]) {
        ((UITableViewHeaderFooterView *)view).backgroundView.backgroundColor = ColorWithRGB(0xF8F9FA);
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    HiddenBar;
    
    ShopOrderModel * model = self.orderModelArray[indexPath.row];
    
    OrderDetailsViewController * orderVC = [OrderDetailsViewController new];
    
    orderVC.ID = model.id;
//    orderVC.disLabel.hidden = YES;
    
    [self.navigationController pushViewController:orderVC animated:YES];
}


- (void)clickItemButton:(NSString *)type{
//    [self.orderModelArray removeAllObjects];
    self.type = type;

    self.orderModelArray = nil;
    [self loadDataWithStatus:type];
}


//- (void)cellClickSureButton:(MyOrderListTableViewCell *)cell{
//
//    [self setupToolBarViewWithInfo:cell.model];
//
//
//}
//
//- (void)cellClickCancleButton:(MyOrderListTableViewCell *)cell{
//
//
//}

- (void)clickItemButton:(NSString *)type WithCell:(MyOrderListTableViewCell *)cell{
    
    if ([type isEqualToString:@"立即使用"]) {
        
        ShopOrderModel * model = cell.model;
        int merchants_goods_is_meituan = [model.merchants_goods_is_meituan intValue];
        if (merchants_goods_is_meituan == 1) {
           
            [self setupToolBarViewWithInfo:cell.model];
        }else{
            
            [self setupToolBarViewWithInfo:cell.model];
            [self updateToolBarViewDataWithInfo:cell.model];
        }
        
    }else if ([type isEqualToString:@"取消订单"]){
        
        UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                       message:@"是否取消该订单？"
                                                                preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault
                                                              handler:^(UIAlertAction * action) {
                                                                  
                                                                  [[ZRNetworkTool sharedTool] cancelGoodsOrderWithGood_id:cell.model.id ResultWithBlock:^(BOOL success, id responseData) {
                                                                     
                                                                      if (success) {
                                                                          
                                                                          UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                                                                                         message:responseData[@"message"]
                                                                                                                                  preferredStyle:UIAlertControllerStyleAlert];
                                                                          
                                                                          UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                                                                                handler:^(UIAlertAction * action) {
                                                                                                                                    
                                                                                                                                    self.orderModelArray = nil;
                                                                                                                                    [self loadDataWithStatus:self.type];                                                          }];
                                                                          
                                                                          [alert addAction:defaultAction];
                                                                          [self presentViewController:alert animated:YES completion:nil];
                                                                      }else{
                                                                          
                                                                          UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                                                                                         message:responseData[@"message"]
                                                                                                                                  preferredStyle:UIAlertControllerStyleAlert];
                                                                          
                                                                          UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                                                                                handler:^(UIAlertAction * action) {
                                                                                                                                    
                                                                                                                                }];
                                                                          
                                                                          [alert addAction:defaultAction];
                                                                          [self presentViewController:alert animated:YES completion:nil];
                                                                      }
                                                                      
                                                                  }];
                                                              }];
        UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel
                                                              handler:^(UIAlertAction * action) {
                                                                  
                                                              }];
        
        [alert addAction:defaultAction];
        [alert addAction:cancelAction];
        [self presentViewController:alert animated:YES completion:nil];
        
        
    }else if ([type isEqualToString:@"删除订单"]){
        
        UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                       message:@"是否删除该订单？"
                                                                preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault
                                                              handler:^(UIAlertAction * action) {
                                                                  
                                                                  [[ZRNetworkTool sharedTool] deleteGoodsOrderWithGood_id:cell.model.id ResultWithBlock:^(BOOL success, id responseData) {
                                                                      
                                                                      self.orderModelArray = nil;
                                                                      [self loadDataWithStatus:self.type];
                                                                  }];
                                                              }];
        UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel
                                                             handler:^(UIAlertAction * action) {
                                                                 
                                                             }];
        
        [alert addAction:defaultAction];
        [alert addAction:cancelAction];
        [self presentViewController:alert animated:YES completion:nil];
        
    }else if ([type isEqualToString:@"立即评价"]){
        
        HiddenBar;
        publishCommitViewController * pushVC = [publishCommitViewController new];
        pushVC.ID = cell.model.id;
        NSArray *array = [cell.model.merchants_goods_img componentsSeparatedByString:@","];
        NSString * goodsStr = [NSString stringWithFormat:@"%@%@",BASEURLSTR,array.firstObject];
        NSURL * goodsUrl = [NSURL URLWithString:goodsStr];
        pushVC.goodUrl = goodsUrl;
        [self.navigationController pushViewController:pushVC animated:YES];
//        NSLog(@"立即评价");
    }else if ([type isEqualToString:@"再来一单"]){
        
        HiddenBar;
        ShopDetailsViewController * detailsVC = [ShopDetailsViewController new];
        detailsVC.ID = cell.model.merchants_goods_merchants_id;
        [self.navigationController pushViewController:detailsVC animated:YES];
//        NSLog(@"再来一单");
    }else if ([type isEqualToString:@"立即付款"]){
        
        HiddenBar;
        self.ID = [NSString stringWithFormat:@"%@",cell.model.id];
        [self setupChoosePayWay];
        //        NSLog(@"再来一单");
    }
}

- (void)updateToolBarViewDataWithInfo:(ShopOrderModel *)model{
    
    if(self.timer){
        
        dispatch_resume(self.timer);
    }else{
        
        __weak __typeof(self)weakSelf = self;
        //    [self.timer startTimerWithSpace:3 block:^(BOOL result) {
        //    }];
        
        //0.创建队列
        dispatch_queue_t queue = dispatch_get_main_queue();
        //1.创建GCD中的定时器
        /*
         第一个参数:创建source的类型 DISPATCH_SOURCE_TYPE_TIMER:定时器
         第二个参数:0
         第三个参数:0
         第四个参数:队列
         */
        dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
        
        //2.设置时间等
        /*
         第一个参数:定时器对象
         第二个参数:DISPATCH_TIME_NOW 表示从现在开始计时
         第三个参数:间隔时间 GCD里面的时间最小单位为 纳秒
         第四个参数:精准度(表示允许的误差,0表示绝对精准)
         */
        dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 3.0 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
        
        //3.要调用的任务
        dispatch_source_set_event_handler(timer, ^{
            
            //        NSLog(@"GCD-----%@",[NSThread currentThread]);dispatch_cancel
            NSString * goods_id = [NSString stringWithFormat:@"%@",model.goods_order_goods_id];
            NSString * barcode = [NSString stringWithFormat:@"%@",model.goods_order_code];
            NSDictionary * dict = @{@"goods_id":goods_id,@"barcode":barcode};
            
            [[ZRNetworkTool sharedTool] monitorMerchantsGoodsBarcodeWithDict:dict WithBlock:^(BOOL success, id responseData) {
                
                if (success) {
                    
                    HiddenBar;
                    DoneDetailViewController * doneVC = [DoneDetailViewController new];
                    doneVC.goods_id = goods_id;
                    doneVC.model = model;
                    
                    [weakSelf.navigationController pushViewController:doneVC animated:YES];
                    
                    [weakSelf clickCloseButton];
                    
                    
                }
            }];
            
        });
        
        //4.开始执行
        dispatch_resume(timer);
        
        //
        self.timer = timer;
    }
    
}

- (void)setupChoosePayWay{
    
    UIToolbar *toolbar = [[UIToolbar alloc]initWithFrame:[UIScreen mainScreen].bounds];
    //样式
    toolbar.barStyle = UIBarStyleBlackTranslucent;//半透明
    //透明度
    toolbar.alpha = 0.5f;
    toolbar.userInteractionEnabled = YES;
    UITapGestureRecognizer *tapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hiddenChooseView)];
    [toolbar addGestureRecognizer:tapGR];
    
    self.chooseToolbar = toolbar;
    [self.tabBarController.view addSubview:self.chooseToolbar];
    
    UIView * couponView = [[UIView alloc] initWithFrame:CGRectMake(0, kScreenH - 215 * SCREENH6, kScreenW, 215 * SCREENH6)];
    
    couponView.backgroundColor = ZRWhiteColor;
    couponView.userInteractionEnabled = YES;
    
    self.chooseView = couponView;
    
    [self.tabBarController.view addSubview:self.chooseView];
    
    
    UIButton * closeButton = [UIButton new];
    
    [closeButton setTitleColor:ZRBlackColor forState:UIControlStateNormal];
    [closeButton setTitle:@"取消" forState:UIControlStateNormal];
    [closeButton addTarget:self action:@selector(clickCancleButton) forControlEvents:UIControlEventTouchUpInside];
    closeButton.titleLabel.font = [UIFont systemFontOfSize:15 * SCREENH6];
    
    [self.chooseView addSubview:closeButton];
    
    
    UILabel * titleLabel = [UILabel new];
    
    titleLabel.text = @"支付方式";
    titleLabel.textColor = ZRBlackColor;
    titleLabel.font = [UIFont boldSystemFontOfSize:17 * SCREENH6];
    
    [self.chooseView addSubview:titleLabel];
    
    
    UIButton * zhifubaoButton = [UIButton new];
    
    zhifubaoButton.tag = 1001;
    [zhifubaoButton setImage:[UIImage imageNamed:@"支付宝支付"] forState:UIControlStateNormal];
    [zhifubaoButton addTarget:self action:@selector(clickPayMoneyButton:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.chooseView addSubview:zhifubaoButton];
    
    UIButton * weixinButton = [UIButton new];
    
    weixinButton.tag = 1002;
    [weixinButton setImage:[UIImage imageNamed:@"微信支付"] forState:UIControlStateNormal];
    [weixinButton addTarget:self action:@selector(clickPayMoneyButton:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.chooseView addSubview:weixinButton];
    
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.chooseView);
        make.top.mas_equalTo(self.chooseView).offset(10 * SCREENH6);
    }];
    
    [closeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.chooseView).offset(10 * SCREENH6);
        make.centerY.mas_equalTo(titleLabel);
    }];
    
    [zhifubaoButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.chooseView).offset(15 * SCREENH6);
        make.trailing.mas_equalTo(self.chooseView.mas_centerX).offset(-5 * SCREENH6);
        make.width.mas_equalTo(158 * SCREENH6);
        make.height.mas_equalTo(80 * SCREENH6);
    }];
    
    [weixinButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.width.height.mas_equalTo(zhifubaoButton);
        make.leading.mas_equalTo(self.chooseView.mas_centerX).offset(5 * SCREENH6);
    }];
}

- (void)clickCancleButton{
    
    [self.chooseView removeFromSuperview];
    [self.chooseToolbar removeFromSuperview];
}

- (void)hiddenChooseView{
    
    [self.chooseView removeFromSuperview];
    [self.chooseToolbar removeFromSuperview];
}

- (void)clickPayMoneyButton:(UIButton *)button{
    
    NSString * user_id = DEF_GET_OBJECT(@"id");
    if (button.tag == 1002) {
    
        NSString * IP = [self getIPAddress];
        NSDictionary * dict = @{@"user_id":user_id,@"goods_order_id":self.ID,@"pay_type":@"WX_APPAPI",@"spbill_create_ip":IP};
        
        [[NetworkTool sharedTools] POST:@"WxjsAPI/payApiCall" parameters:dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            int code = [responseObject[@"code"] intValue];
            
            if (code == 200) {
                NSDictionary * data = responseObject[@"data"];
                [WXApiManager sharedManager].delegate = self;
                [[WXApiManager sharedManager] weiXinPayWithDic:data];
            }
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
        }];
    }else if(button.tag == 1001){
        //ZFB_APPAPI
//        NSString * user_id = DEF_GET_OBJECT(@"id");
        NSDictionary * dict = @{@"user_id":user_id,@"goods_order_id":self.ID,@"pay_type":@"ZFB_APPAPI"};
        
        [[NetworkTool sharedTools] POST:@"WxjsAPI/payApiCall" parameters:dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            int code = [responseObject[@"code"] intValue];
            
            if (code == 200) {
                
                NSString * data = [NSString stringWithFormat:@"%@",responseObject[@"data"]];
                NSString *appScheme = @"FindifZhifubao20181105";
                
                [[AlipaySDK defaultService] payOrder:data fromScheme:appScheme callback:^(NSDictionary *resultDic) {
                    
                   
                }];
            }
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
        }];
        
    }
    
    [self.chooseView removeFromSuperview];
    [self.chooseToolbar removeFromSuperview];
}


- (void)setupToolBarViewWithInfo:(ShopOrderModel *)model{
    
    UIToolbar *toolbar = [[UIToolbar alloc]initWithFrame:[UIScreen mainScreen].bounds];
    //样式
    toolbar.barStyle = UIBarStyleBlackTranslucent;//半透明
    //透明度
    toolbar.alpha = 0.5f;
    toolbar.userInteractionEnabled = YES;
    UITapGestureRecognizer *tapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction)];
    [toolbar addGestureRecognizer:tapGR];
    
    self.toolbar = toolbar;
    [self.tabBarController.view addSubview:self.toolbar];
    
    UIView * whiteView = [[UIView alloc] init];
    
    whiteView.backgroundColor = ZRWhiteColor;
    whiteView.userInteractionEnabled = YES;
    whiteView.layer.cornerRadius = 5 * SCREENH6;
    whiteView.layer.masksToBounds = YES;
    
    self.whiteView = whiteView;
    
    [self.tabBarController.view addSubview:self.whiteView];
    
    
    UIButton * closeButton = [UIButton new];
    
    [closeButton setImage:[UIImage imageNamed:@"关闭"] forState:UIControlStateNormal];
    [closeButton addTarget:self action:@selector(clickCloseButton) forControlEvents:UIControlEventTouchUpInside];
    
    [self.whiteView addSubview:closeButton];
    
    
    UILabel * titleLabel = [UILabel new];
    
    titleLabel.text = model.merchants_goods_name;
    titleLabel.textColor = ZRBlackColor;
    titleLabel.font = [UIFont boldSystemFontOfSize:16 * SCREENH6];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    
    [self.whiteView addSubview:titleLabel];
   
    UILabel * exploreLabel = [UILabel new];
    
    exploreLabel.text = @"核销码";
    exploreLabel.textColor = ZRBlackColor;
    exploreLabel.font = [UIFont systemFontOfSize:15 * SCREENH6];
    exploreLabel.textAlignment = NSTextAlignmentLeft;
    
    [self.whiteView addSubview:exploreLabel];
    
    UILabel * codeLabel = [UILabel new];
    
    codeLabel.textColor = ZRBlackColor;
    codeLabel.font = [UIFont boldSystemFontOfSize:15 * SCREENH6];
    codeLabel.textAlignment = NSTextAlignmentRight;
    
    [self.whiteView addSubview:codeLabel];
    
    UIView * lineView = [UIView new];
    
    lineView.backgroundColor = ColorWithRGB(0xe4e4e4);
    
    [self.whiteView addSubview:lineView];
    
    UILabel * subLabel = [UILabel new];
    
    subLabel.textColor = [UIColor grayColor];
    subLabel.text = @"向商家出示以上券码即可消费";
    subLabel.font = [UIFont systemFontOfSize:14 * SCREENH6];
    
    [self.whiteView addSubview:subLabel];
    
    NSString * user_id = [NSString stringWithFormat:@"%@",model.goods_order_user_id];
    NSString * goods_id = [NSString stringWithFormat:@"%@",model.goods_order_goods_id];
    NSString * goods_order_code = [NSString stringWithFormat:@"%@",model.goods_order_code];
    NSDictionary * dict = @{@"user_id":user_id,@"goods_id":goods_id,@"barcode":goods_order_code};
    NSData *data;
    int merchants_goods_is_meituan = [model.merchants_goods_is_meituan intValue];
    if (merchants_goods_is_meituan == 1) {
        
        NSString * code = model.goods_order_meituan_code;
        codeLabel.text = [NSString stringWithFormat:@"%@",model.goods_order_meituan_code];
        data =[code dataUsingEncoding:NSUTF8StringEncoding];
    }else{
        
        codeLabel.text = [NSString stringWithFormat:@"%@",model.goods_order_code];
        data= [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
    }
    
    // 1.创建过滤器，这里的@"CIQRCodeGenerator"是固定的
    CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    
    // 2.恢复默认设置
    [filter setDefaults];
    // 3. 给过滤器添加数据
    
    // 注意，这里的value必须是NSData类型
    [filter setValue:data forKeyPath:@"inputMessage"];
    
    // 4. 生成二维码
    CIImage *outputImage = [filter outputImage];

    
    UIImageView * codeImageView = [UIImageView new];
    
    codeImageView.image = [self creatNonInterpolatedUIImageFormCIImage:outputImage withSize:120 * SCREENH6];
    
    [self.whiteView addSubview:codeImageView];
    
    
    [self.whiteView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view);
        make.centerY.mas_equalTo(self.view);
        make.width.mas_equalTo(320 * SCREENH6);
        make.height.mas_equalTo(265 * SCREENH6);
    }];
    
    [closeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.mas_equalTo(self.whiteView).offset(-10 * SCREENH6);
        make.top.mas_equalTo(self.whiteView).offset(10 * SCREENH6);
        make.width.height.mas_equalTo(15 * SCREENH6);
    }];
    
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.leading.mas_equalTo(self.whiteView).offset(10 * SCREENH6);
//        make.trailing.mas_equalTo(closeButton.mas_leading).offset(-10 * SCREENH6);
        make.centerX.mas_equalTo(self.whiteView);
        make.width.mas_equalTo(260 * SCREENH6);
        make.top.mas_equalTo(self.whiteView).offset(15 * SCREENH6);
    }];
    
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.mas_equalTo(self.whiteView);
        make.height.mas_equalTo(1 * SCREENH6);
        make.top.mas_equalTo(titleLabel.mas_bottom).offset(10 * SCREENH6);
    }];
    
    [codeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.mas_equalTo(self.whiteView).offset(-15 * SCREENH6);
        make.top.mas_equalTo(lineView.mas_bottom).offset(10 * SCREENH6);
    }];
    
    [exploreLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.whiteView).offset(15 * SCREENH6);
        make.centerY.mas_equalTo(codeLabel);
    }];

    [codeImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.whiteView);
        make.width.height.mas_equalTo(140 * SCREENH6);
        make.top.mas_equalTo(exploreLabel.mas_bottom).offset(10 * SCREENH6);
    }];
    
    [subLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.whiteView);
        make.top.mas_equalTo(codeImageView.mas_bottom).offset(15 * SCREENH6);
    }];
}


- (void)clickCloseButton{
    
    [self.toolbar removeFromSuperview];
    [self.whiteView removeFromSuperview];
    
    if (self.timer) {
        
        dispatch_suspend(self.timer);
    }
    
}

- (void)tapAction{
    
    [self.toolbar removeFromSuperview];
    [self.whiteView removeFromSuperview];
    
    if (self.timer) {
        
        dispatch_suspend(self.timer);
    }
}


#pragma mark - TableView 占位图
- (NSString *)xy_noDataViewMessage {
    
    return @"暂无订单";
}

- (UIColor *)xy_noDataViewMessageColor {
    
    return [UIColor blackColor];
}


- (UIImage *)creatNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGFloat)size
{
    CGRect extent = CGRectIntegral(image.extent);
    CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
    
    // 1. 创建bitmap
    size_t width = CGRectGetWidth(extent) * scale;
    size_t height = CGRectGetHeight(extent) * scale;
    CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
    CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
    CIContext *context = [CIContext contextWithOptions:nil];
    CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];
    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
    CGContextScaleCTM(bitmapRef, scale, scale);
    CGContextDrawImage(bitmapRef, extent, bitmapImage);
    
    // 2.保存bitmap图片
    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
    CGContextRelease(bitmapRef);
    CGImageRelease(bitmapImage);
    return [UIImage imageWithCGImage:scaledImage];
}

// 获取设备IP地址
-(NSString *)getIPAddress {
    NSString *address = @"error";
    struct ifaddrs *interfaces = NULL;
    struct ifaddrs *temp_addr = NULL;
    int success = 0;
    // 检索当前接口,在成功时,返回0
    success = getifaddrs(&interfaces);
    if (success == 0) {
        // 循环链表的接口
        temp_addr = interfaces;
        while(temp_addr != NULL) {
            if(temp_addr->ifa_addr->sa_family == AF_INET) {
                // 检查接口是否en0 wifi连接在iPhone上
                if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
                    // 得到NSString从C字符串
                    address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
                }
            }
            temp_addr = temp_addr->ifa_next;
        }
    }
    // 释放内存
    freeifaddrs(interfaces);
    return address;
}

- (void)managerDidRecvPaymentResponse:(PayResp *)response{
    
    //支付返回结果，实际支付结果需要去微信服务器端查询
    //    NSString *strMsg,*strTitle = [NSString stringWithFormat:@"支付结果"];
    
    switch (response.errCode) {
        case WXSuccess:
            
            [self showSuccessPushOrder];
            break;
        case -2:
            //用户取消
            [self showErrorWithString:@"已取消支付"];
            break;
        default:
            
            [self showErrorWithString:response.errStr];
            break;
    }
    
}

- (void)showSuccessPushOrder{
    
    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                   message:@"支付成功，快去使用吧！"
                                                            preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault
                                                          handler:^(UIAlertAction * action) {
                                                              
                                                              
                                                              [self loadDataWithStatus:@"10"];
                                                          }];
    
    [alert addAction:defaultAction];
    [self presentViewController:alert animated:YES completion:nil];
}


- (void)showErrorWithString:(NSString *)string{
    
    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                   message:string
                                                            preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault
                                                          handler:^(UIAlertAction * action) {
                                                              
                                                              
                                                          }];
    
    [alert addAction:defaultAction];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)zhifuNotification:(NSNotification *)noti{
    
    NSString * memo = noti.userInfo[@"memo"];
    
    if ([noti.userInfo[@"resultStatus"] isEqualToString:@"9000"]) {
        
        [self showSuccessPushOrder];
    }else{
        
        [self showErrorWithString:memo];
    }
}

- (void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)updateData{
    
    [self loadDataWithStatus:self.type];    
    [self.tableView.mj_header endRefreshing];
}

@end
